package service

import (
	"flare-admin/db/sqlc/micro"
	micro2 "flare-admin/service/dto/micro"
	"github.com/gin-gonic/gin"
	"github.com/jackc/pgx/v5/pgtype"
	"github.com/sirupsen/logrus"
)

func (s *Service) GetAllPattern(ctx *gin.Context) ([]micro2.PatternDTO, error) {
	patterns, err := s.dao.Micro.SelectAllPattern(ctx)
	if err != nil {
		logrus.Errorf("[service] - [GetAllPattern] - failed to get all pattern: %v", err)
	}
	return micro2.PatternDao2DTOs(patterns), nil
}

func (s *Service) AddPattern(ctx *gin.Context, patternDto *micro2.PatternDTO) (any, error) {
	id, err := s.dao.Micro.InsertPattern(ctx, micro.InsertPatternParams{
		Name:        patternDto.Name,
		Description: patternDto.Desc,
		GraphData:   patternDto.GraphData,
	})
	if err != nil {
		logrus.Errorf("[service] - [AddPattern] - failed to add new pattern: %v", err)
	}
	return id, err
}

func (s *Service) AddPatternMatchResult(ctx *gin.Context, resultDTO *micro2.PatternMatchResultDTO) (any, error) {
	invokeTime := pgtype.Timestamp{}
	err := invokeTime.Scan(resultDTO.InvokeTime)
	if err != nil {
		logrus.Errorf("[service] - [AddPatternMatchResult] - failed to scan timestamp: %v", err)
		return nil, err
	}
	analyseTime := pgtype.Timestamp{}
	err = analyseTime.Scan(resultDTO.AnalyseTime)
	if err != nil {
		logrus.Errorf("[service] - [AddPatternMatchResult] - failed to scan timestamp: %v", err)
		return nil, err
	}
	return s.dao.Micro.InsertPatternMatchResult(ctx, micro.InsertPatternMatchResultParams{
		PatternID:      int32(resultDTO.PatternID),
		CybertwinID:    int32(resultDTO.CybertwinID),
		CybertwinLabel: resultDTO.CybertwinLabel,
		InvokeTime:     invokeTime,
		AnalyseTime:    analyseTime,
	})
}

func (s *Service) GetAllPatternMatchResult(ctx *gin.Context) ([]micro.SelectPatternMatchResultRow, error) {
	return s.dao.Micro.SelectPatternMatchResult(ctx)
}
